<?php
namespace app\api\controller;

use app\common\controller\Frontend;

class File extends Frontend
{
    public  function upload(){
        $file = request()->file('file');
        $filesize = filesize($file);
        $filesize  = $this->trans_byte($filesize);
        $OriginalName = $file->getOriginalName();
        try {
            $savename = \think\facade\Filesystem::disk('public')->putFile( 'file', $file,'date()');
            $savename = str_replace('\\','/',$savename);
            $url = config('filesystem.disks.public.url').'/'.$savename."#".$OriginalName;
            $data = [
                "path"  =>  $this->request->scheme().'://'.$_SERVER['HTTP_HOST'].$url,
                "url"   =>  $url,
                "original_name"  =>  $OriginalName,
                "filesize" => $filesize
            ];
            $this->success('',$data);
        } catch (Exception $e){
            $this->error($e->getMessage());
        }
    }

    private function trans_byte($byte){
        $KB = 1024;
        $MB = 1024 * $KB;
        $GB = 1024 * $MB;
        $TB = 1024 * $GB;
        if($byte < $KB){
            return $byte." B";
        } else if($byte < $MB){
            return round($byte / $KB, 2)." KB";
        } else if($byte < $GB){
            return round($byte / $MB, 2)." MB";
        } else if($byte < $TB){
            return round($byte / $GB, 2)." GB";
        } else {
            return round($byte / $TB, 2)." TB";
        }
    }
}
